package com.example.oversea_home_spring.controller;


import com.example.oversea_home_spring.bean.User;
import com.example.oversea_home_spring.service.UserService;
import com.example.oversea_home_spring.uitl.CodeMsg;
import com.example.oversea_home_spring.uitl.DateUtil;
import com.example.oversea_home_spring.uitl.Result;
import com.example.oversea_home_spring.uitl.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@CrossOrigin//跨域
@RequestMapping("user")
public class LoginController {

    @Autowired
    UserService userService;

    //登录
    @GetMapping("login")
    public Result<User> login(String account,String password){
        User user = userService.login(account,password);
        if(user==null){
            return Result.error(CodeMsg.LOGIN_ERROR);
        }
        else {
            System.out.println(user);
            System.out.println(user.getStatus());
            if(user.getStatus()==2)
            {
                return Result.error(CodeMsg.ACCOUNT_LOGOUT);
            }
            return Result.success(user);
        }
    }

    //用户注册
    @RequestMapping("register")
    public Result<Integer> register(User user){
        //判断是否已经存在
        User user2 = userService.login(user.getAccount(),user.getPassword());
        if(user2==null){
            //设置id
            String id = UUIDUtil.uuid();
            user.setId(id);
            //设置日期
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = new Date();
            user.setCreateTime(sdf.format(date));
            user.setUpdateTime(sdf.format(date));
            //设置状态
            user.setStatus((long) 1);
            int i = userService.register(user);
            if(i > 0){
                return Result.success(i);
            }
        }
        else {
            System.out.println(user2.getId());
        }
        return Result.error(CodeMsg.REGISTER_ERROR);
    }

    //用户修改自身信息
    @PutMapping("updateInfo")
    public Result<Integer> updateMyInfo(User user){
        user.setUpdateTime(DateUtil.myDate());
        int isOk = userService.updateMyInfo(user);
        if(isOk > 0){
            return Result.success(isOk);
        }
        return Result.error(CodeMsg.UPDATE_INFO_ERROR);
    }



}
